package com.arpa.ntocc.basic.api.controller;


import cn.hutool.core.collection.IterUtil;
import cn.hutool.core.map.MapUtil;
import com.arpa.core.web.MediaTypes;
import com.arpa.core.web.Result;
import com.arpa.ntocc.common.common.Page;
import com.arpa.ntocc.common.common.constant.StrConsts;
import com.arpa.ntocc.common.common.util.UserUtil;
import com.arpa.ntocc.common.controller.BaseController;
import com.arpa.ntocc.common.domain.dto.DictDTO;
import com.arpa.ntocc.common.domain.entity.Dict;
import com.arpa.ntocc.common.domain.vo.DictVO;
import com.arpa.ntocc.common.security.annotation.NeedLogin;
import com.arpa.ntocc.common.security.annotation.NoRepeat;
import com.arpa.ntocc.common.service.IDictService;
import io.swagger.annotations.*;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 数据字典表 Controller
 * </p>
 *
 * @author liuyj
 * @since 2019-11-25
 */
@Api(tags = "数据字典表")
@RestController
@RequestMapping(value="/dict", produces = "application/json;charset=UTF-8")
@Log4j2
public class DictController extends BaseController {

   @Autowired
   private IDictService  iDictService;

    private final static String CODE_ALREADY_EXSITS = "编码已存在";
    /**
     * 获取 数据字典表 列表（管理）
     *
     * @param dictDTO
     * @param request
     * @return
     */
    @ApiOperation(value = "获取 数据字典表 列表（管理）", notes = "获取 数据字典表 列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "Authorization", value = "授权token", required = true, paramType = "header", dataType = "String", defaultValue = "Bearer "),
            @ApiImplicitParam(name = "deviceId", value = "设备id", paramType = "header", dataType = "string", defaultValue = "0000000000")
    })
    @ApiResponses(@ApiResponse(code = 0, message = "success", response = DictVO.class))
    @NeedLogin
    @GetMapping()
    public Result list(DictDTO dictDTO, HttpServletRequest request) {
        try {
            dictDTO.setBranchCode(UserUtil.getBranchCode());
            DictVO dictVOSum = iDictService.queryListSum(dictDTO);
            List<DictVO> dictVOList = iDictService.queryList(dictDTO);
            Page returnPage = new Page(dictDTO.getPageNum(),dictDTO.getPageSize());
            returnPage.setRecords(dictVOList);
            returnPage.setTotal(dictVOSum.getTotal());
            returnPage.setSumObject(dictVOSum);
            return Result.ok().data(returnPage);
        } catch (Exception e) {
            log.error(StrConsts.CATCH_MESSAGE,e);
            return Result.error(e.getMessage());
        }
    }

    /**
     * 获取 数据字典表 列表（接口）
     *
     * @param request
     * @return
     */
    @ApiOperation(value = "获取 数据字典表 列表（接口）", notes = "获取 数据字典表 列表（接口使用，获取的缓存数据）")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "Authorization", value = "授权token", required = true, paramType = "header", dataType = "String", defaultValue = "Bearer "),
            @ApiImplicitParam(name = "deviceId", value = "设备id", paramType = "header", dataType = "string", defaultValue = "0000000000"),
            @ApiImplicitParam(name = "types", value = "字典类型，多个以,号隔开 如 vehicleLength,vehicleZhoushu", required = true, paramType = "query", dataType = "List")
    })
    @ApiResponses(@ApiResponse(code = 0, message = "success", response = DictVO.class))
    @NeedLogin
    @GetMapping("listDict")
    public Result listDict(@RequestParam List<String> types, HttpServletRequest request) {
        try {
            List<DictVO> dictVOList = iDictService.queryCacheList(types);
            return Result.ok().data(dictVOList);
        } catch (Exception e) {
            log.error(StrConsts.CATCH_MESSAGE,e);
            return Result.error(e.getMessage());
        }
    }

    /**
     * 添加 数据字典表
     *
     * @param entity Dict
     * @param request
     * @return
     */
    @ApiOperation(value = "添加 数据字典表 ", notes = "添加 数据字典表 ")
    @ApiImplicitParams({
    @ApiImplicitParam(name = "Authorization", value = "授权token", required = true, paramType = "header", dataType = "String", defaultValue = "Bearer 123456"),
    @ApiImplicitParam(name = "deviceId", value = "设备id", paramType = "header", dataType = "string", defaultValue = "0000000000")
    })
    @NeedLogin
    @NoRepeat(time = 2000)
    @PostMapping()
    public Result create(@Valid Dict entity, HttpServletRequest request) {
        try {
            entity.setBranchCode(UserUtil.getBranchCode());
            boolean result = iDictService.save(entity);
            if (result){
                return Result.ok("添加成功");
            }else{
                return Result.error(1,CODE_ALREADY_EXSITS);
            }
        } catch (Exception e) {
            log.error(StrConsts.CATCH_MESSAGE,e);
            return Result.error(e.getMessage());
        }
    }

    /**
    * 获取数据字典表详情
    *
    * @param id
    * @param request
    * @return
    */
    @ApiOperation(value = "获取数据字典表详情", notes = "获取数据字典表详情")
    @ApiImplicitParams({
        @ApiImplicitParam(name = "Authorization", value = "授权token", required = true, paramType = "header", dataType = "String", defaultValue = "Bearer 123456"),
        @ApiImplicitParam(name = "deviceId", value = "设备id", paramType = "header", dataType = "string", defaultValue = "0000000000"),
        @ApiImplicitParam(name = "code", value = "数据字典表code", paramType = "path", dataType = "String")
    })
    @NeedLogin
    @GetMapping(value = "/{id}")
    public Result dict(@PathVariable String id, HttpServletRequest request) {
        try {
            Dict entity = iDictService.getById(id);
            return Result.ok().data(entity);
        } catch (Exception e) {
            log.error(StrConsts.CATCH_MESSAGE,e);
            return Result.error(e.getMessage());
        }
    }


    /**
     * 修改数据字典表
     *
     * @param entity 数据字典表
     * @param request
     * @return
     */
    @ApiOperation(value = "修改数据字典表", notes = "修改数据字典表")
    @ApiImplicitParams({
        @ApiImplicitParam(name = "Authorization", value = "授权token", required = true, paramType = "header", dataType = "String", defaultValue = "Bearer "),
        @ApiImplicitParam(name = "deviceId", value = "设备id", paramType = "header", dataType = "string", defaultValue = "0000000000")
    })
    @NeedLogin
    @PutMapping()
    public Result update(@Valid DictDTO entity, HttpServletRequest request) {
        if(null == entity.getId()){
            return Result.error("id不能为空");
        }
        DictDTO query=new DictDTO();
        query.setCode(entity.getCode());
        query.setType(entity.getType());
        query.setBranchCode(UserUtil.getBranchCode());
        List<DictVO> list =iDictService.queryList(query);
        if(CollectionUtils.isNotEmpty(list)){
            if(list.size()>1){
                return Result.error(1,CODE_ALREADY_EXSITS);
            }
            if(!list.get(0).getId().equals(entity.getId())){
                return Result.error(1,CODE_ALREADY_EXSITS);
            }
        }
        int updateNum = iDictService.updateByCode(entity);
        if(updateNum == 0){
            return Result.error("没有更新数据！code:"+entity.getCode());
        }else{
            return Result.ok("修改成功,更新"+updateNum+"条数据！");
        }
    }

    /**
     * 删除 数据字典表
     *
     * @param ids
     * @param request
     * @return
     */
    @ApiOperation(value = "删除 数据字典表 ", notes = "删除 数据字典表 ", produces = MediaTypes.JSON_UTF_8)
    @ApiImplicitParams({
        @ApiImplicitParam(name = "Authorization", value = "授权token", required = true, paramType = "header", dataType = "String", defaultValue = "Bearer "),
        @ApiImplicitParam(name = "deviceId", value = "设备id", paramType = "header", dataType = "string", defaultValue = "0000000000"),
        @ApiImplicitParam(name = "ids", value = "ids", required = true, paramType = "query", dataType = "List")
    })
    @NeedLogin
    @DeleteMapping(value = "")
    public Result batchdel(@RequestParam List<String> ids, HttpServletRequest request) {
        iDictService.removeAndFlushCache(ids);
        return Result.ok("删除成功");
    }

    /**
     * 品牌停用
     *
     * @param codes 品牌code
     * @param request
     * @return
     */
    @ApiOperation(value = "数据字典停用", notes = "数据字典停用")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "Authorization", value = "授权token", required = true, paramType = "header", dataType = "String", defaultValue = "Bearer "),
            @ApiImplicitParam(name = "deviceId", value = "设备id", paramType = "header", dataType = "string", defaultValue = "0000000000"),
    })
    @NeedLogin
    @PutMapping(value = "/unactive")
    public Result unactive(@RequestParam List<String> codes,@RequestParam String type, HttpServletRequest request) {
        if(IterUtil.isEmpty(codes)){
            return Result.error("code不能为空");
        }
        Map<String, Object> result = iDictService.batchUpdateStatus(codes,1,type);
        Integer success = MapUtil.getInt(result, "success");
        List<String> useName = MapUtil.get(result, "useName", List.class);
        int failNum = codes.size() - success;
        StringBuffer buffer = new StringBuffer();
        buffer.append("停用成功" + success + "条；失败" + failNum + "条；");
        if(IterUtil.isNotEmpty(useName)){
            for (String m:useName) {
                buffer.append("<br><font color='red'>品牌【"+m+"】停用失败，商品正在使用中;</font>");
            }
        }
        return Result.ok(buffer.toString());

    }

    /**
     * 数据字典启用
     *
     * @param codes
     * @param request
     * @return
     */
    @ApiOperation(value = "数据字典启用", notes = "数据字典启用")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "Authorization", value = "授权token", required = true, paramType = "header", dataType = "String", defaultValue = "Bearer "),
            @ApiImplicitParam(name = "deviceId", value = "设备id", paramType = "header", dataType = "string", defaultValue = "0000000000"),
            @ApiImplicitParam(name = "codes", value = "codes", required = true, paramType = "query", dataType = "List")
    })
    @NeedLogin
    @PutMapping(value = "/active")
    public Result active(@RequestParam List<String> codes,@RequestParam String type,HttpServletRequest request) {
        if(IterUtil.isEmpty(codes)){
            return Result.error("codes不能为空");
        }
        Map<String, Object> result = iDictService.batchUpdateStatus(codes, 0,type);
        Integer success = MapUtil.getInt(result, "success");
        int failNum = codes.size() - success;
        return Result.ok("启用成功" + success + "条；失败" + failNum + "条；");
    }

 }
